/**
 * 
 */

package com.trydofor.id.mess;

import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;

import com.trydofor.id.core.A9Loader;
import com.trydofor.id.core.ApiExceptions;
import com.trydofor.id.core.Range;

/**
 * @author : Shi Rongjiu (www.trydofor.com)
 */
public class LazyLongLoader implements A9Loader<Range> {
    
    private final AtomicLong    uniqueCq = new AtomicLong();
    private final AtomicBoolean loadExcp = new AtomicBoolean(false);
    private final AtomicBoolean dealExcp = new AtomicBoolean(false);
    private final AtomicBoolean slowLoad = new AtomicBoolean(false);
    private final int           load;
    
    public LazyLongLoader(int first, int load) {
        this.load = load;
        uniqueCq.set(first);
    }
    
    @Override
    public Range heavyLoad() throws Exception {
        if (slowLoad.get()) Thread.sleep(100);
        final long cq = uniqueCq.getAndAdd(load);
        if (loadExcp.get()) throw new Exception("throw an Exception when cq=" + cq);
        Range r = new Range(cq, cq + load - 1);
        return r;
    }
    
    @Override
    public void handleException(Exception e) {
        final boolean ex = dealExcp.get();
        if (ex) {
            ApiExceptions.throwFakeException(e);
        }
    }
    
    public void setThrowOnLoad(boolean b) {
        loadExcp.set(b);
    }
    
    public void setThrowOnHandle(boolean b) {
        dealExcp.set(b);
    }
    
    public void setSlowLoad(boolean b) {
        slowLoad.set(b);
    }
}
